package cn.song.rabbitmq.listener;


import cn.hutool.json.JSONConfig;
import cn.song.common.R;
import cn.song.rabbitmq.MqMessage;
import cn.song.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import static cn.hutool.json.JSONUtil.toJsonStr;
import static cn.song.rabbitmq.config.QueueExchagePath.INSERT;
import static cn.song.rabbitmq.config.QueueExchagePath.ORDER;


/**
 * 基于注解声明队列和交换机
 *
 * @author SongRenShuo
 * @date 2023-12-27
 */
@Slf4j
@Configuration
public class FanoutNoteConfig {


    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private RabbitTemplate rabbitTemplate;



    /**
     * 订单 - 添加
     *
     * @date 2024/08/23
     * @author SongRenShuo
     */
    @RabbitListener(bindings = @QueueBinding(
            // 队列名称
            value = @Queue(name = INSERT, durable = "true"),
            // 交换机名称
            exchange = @Exchange(name = ORDER),
            // 路由键
            key = {INSERT},
            arguments = {
                    // 单活跃消费者
                    @Argument(name = "x-single-active-consumer", value = "true")
            }
    ))
    public void listenDirectQueue01(MqMessage mqMessage) {
        String jsonStr = toJsonStr(mqMessage);
        log.info("RabbitMQ消息队列 消费者端口：{} 消费者接收到,模块：{}  交换机：" + ORDER + ",路由键：" + INSERT + "的消息：【{}】", "serverConfig.getPort()", mqMessage.getMessage(), jsonStr);

        MqMessage mqMessageBak = new MqMessage<>(mqMessage);
        Object data = mqMessage.getData();
        String orderId = "";
        R result = R.failed("");
        try (Jedis jedis = jedisPool.getResource()) {
            JSONConfig jsonConfig = JSONConfig.create();
            jsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");

            String shuju = toJsonStr(data,jsonConfig);


            // 添加数据库
             result = R.success();
            log.info("订单 - 添加 ----异步线程执行结果：{}", result);
            if (result.isCode()) {
                removeOrderFromQueue01(jedis, shuju, orderId);
            } else {
                log.error("订单 - 添加 ----异步线程执行结果失败：{}", result);
                boolean contains = result.getMsg().contains("扣除失败-扣除失败");
                if (contains) {
                    rabbitTemplate.convertAndSend(ORDER, INSERT, mqMessageBak);
                }
            }
        } catch (Exception e) {
            result.setMsg(e.getMessage());
            log.error("RabbitMQ消息队列 异常,模块：{}  交换机：" + ORDER + ",路由键：" + INSERT + "的消息：【{}】", mqMessage.getMessage(), jsonStr, e);
            throw new RuntimeException(e);
        } finally {
            // R r = new R();
            log.info("RabbitMQ消息队列 执行结果 模块：{}  交换机：" + ORDER + ",路由键：" + INSERT + "订单-添加-执行结果：{} 消息体：{}", mqMessage.getMessage(),toJsonStr(result), jsonStr);
        }
    }

    /**
     * 从缓存队列中移除已完成处理的订单数据
     *
     * @param jedis      Jedis实例
     * @param shuju      缓存中的订单JSON字符串
     * @param ysddBianma 订单编号
     */
    public void removeOrderFromQueue01(Jedis jedis, String shuju, String ysddBianma) {
        Long jiekou = jedis.lrem("jiekou", 1, shuju);
        Long ysdd = jedis.lrem("ysdd", 1, ysddBianma);
    }
}
